<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;


class UserController extends Controller
{
    public function show($uid)
    {
        $user = User::where('id', $uid)->with(['posts'])->withCount(['posts', 'fans', 'stars'])->first();
        $user->concerned = $user->concerned() ? true:false;
        $myidos = \Auth::user()->stars()->get()->pluck('id')->toArray();
        $user_idos = $user->stars()->get()->pluck('id')->toArray();
        $user_fans = $user->fans()->get()->pluck('id')->toArray();
        $user->stars = User::whereIn('id',$user_idos)->withCount(['posts', 'fans', 'stars'])->get();
        $user->fans = User::whereIn('id',$user_fans)->withCount(['posts', 'fans', 'stars'])->get();
        foreach ($user->fans as $fan){
             if(in_array($fan->id,$myidos)){
                 $fan->concerned = true;
             }else{
                 $fan->concerned = false;
             }
        }
        foreach ($user->stars as $star){
            if(in_array($star->id,$myidos)){
                $star->concerned = true;
            }else{
                $star->concerned = false;
            }
        }

        return view('user.index', compact( 'user'));
    }

    public function concern(User $user)
    {
        $relation = $user->concerned();
        if (!$relation) {
            $user->fans()->attach([
                'fan_id' => \Auth::id()
            ]);
            return res('','取消关注');
        }else{
            $relation->delete();
            return res('','关注');
        }

    }


}
